package com.huatai.verity.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: ht-system
 * @description: 生成公私钥
 * @author: songxiude
 * @create: 2023-07-20 13:36
 **/
@Slf4j
public class KeyGeneratorUtil {
	/**
	 * 加密算法
	 */
	private static final String KEY_ALGORITHM = "RSA";

	/**
	 * 获取公私钥
	 * @return
	 */
	public static Map<String,String> generater(){
		HashMap<String, String> hashMap = new HashMap<>();
		try {
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
			keyPairGenerator.initialize(1024);
			KeyPair keyPair = keyPairGenerator.genKeyPair();
			RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
			RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
			hashMap.put("privateKey",new String(Base64.getEncoder().encode(priKey.getEncoded())));
			hashMap.put("publicKey",new String(Base64.getEncoder().encode(pubKey.getEncoded())));
			return hashMap;
		}catch (NoSuchAlgorithmException e){
			log.error(e.getMessage());
		}
		return hashMap;
	}
}
